#include "udp_client.hpp"
#include "err.hpp"
#include <pthread.h>

static void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << "serverip serverport\n"
              << std::endl;
}

void *recever(void *args) // 接收
{
    int sock = *(static_cast<int *>(args));
    while (true)
    {
        char buffer[1024];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        int n = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&temp, &len);
        if (n > 0)
        {
            buffer[n] = '\0';
            std::cout << buffer << std::endl;
        }
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    std::string serverip = argv[1];
    u_int16_t serverport = atoi(argv[2]);
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "creat socket error " << std::endl;
        exit(SOCKET_ERR);
    }
    // 客户端要bind，但不需要自己bind，OS会自己帮我们bind，该port由OS随机分配

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    pthread_t tid;
    pthread_create(&tid, nullptr, recever, &sock);

    while (true)
    {
        std::string message;
        std::cerr << "Please Enter Your Message# ";
        getline(std::cin, message);

        // 发送
        sendto(sock, message.c_str(), message.size(), 0, (sockaddr *)&server, sizeof(server));
    }
    return 0;
}